package com.dataStructure.Map;

import java.util.*;

/**
 * 线性映射，查找，更新，移除，键值对的时间都是线性时间，因为我们底层维持一个集合（元素为键值对容器），
 * 每一次增删改操作都是基于 findEntry() 方式
 * @param <K>
 * @param <V>
 */
public class MyLinerMap<K,V> implements Map<K,V> {
    private List<Entry<K,V>> entries = new ArrayList<>();


    /**
     * Returns the entry that contains the target key, or null if there is none.
     */
    private Entry<K,V> findEntry(Object target) {
        for (Entry<K, V> e : entries) {
            if (this.equal(target,e.getKey())) {
                return e;
            }
        }
        return null;
    }

    public List<Entry<K, V>> getEntries() {
        return entries;
    }

    private Boolean equal(Object target, Object obj) {
        return obj.equals(target);
    }


    @Override
    public int size() {
        return entries.size();
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public boolean containsKey(Object key) {
        return false;
    }

    @Override
    public boolean containsValue(Object value) {
        for (Entry<K, V> entry : entries) {
           if ( entry.getValue().equals(value)){
               return true;
           }
        }
        return false;
    }

    @Override
    public V get(Object key) {
        Entry<K, V> entry = this.findEntry(key);
        if (entry == null){
            return null;
        } else {
            return entry.getValue();
        }

    }

    @Override
    public V put(K key, V value) {
        Entry<K, V> entry = this.findEntry(key);
        if (entry == null) {
            com.dataStructure.Map.Entry<K, V> kvEntry = new com.dataStructure.Map.Entry<>(key, value);
            entries.add(kvEntry);
            return null;
        } else {
            V value1 = entry.getValue();
            entry.setValue(value);
            return value1;
        }

    }

    /**
     * 返回删除之后的值
     * @param key
     * @return
     */
    @Override
    public V remove(Object key) {
        Entry<K, V> entry = this.findEntry(key);
        if (entry == null) {
            return null;
        }
        else {
            V value = entry.getValue();
            entries.remove(entry);
            return value;
        }

    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {

    }

    @Override
    public void clear() {

    }

    @Override
    public Set<K> keySet() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return null;
    }
}
